var express = require('express');
var router = express.Router();
var sql = require("../utils/sql")
const path = require("path");
const fs = require("fs")
let moment = require("moment");
const multer = require('multer');
const upload = multer({ dest: path.join(__dirname, '../public/admin/images/') });


/* 后端管理系统登陆页面 */
router.get('/', function (req, res, next) {
  res.redirect("/admin/login.html");
});

// 管理员登陆 
router.get('/login', function (req, res, next) {
  let { uname, pass } = req.query;
  if (uname !== "" && pass !== "") {
    // 链接数据库拿到管理员账号密码
    sql("select * from guanli where username=?", [uname], function (data) {
      // 查找不到长度为0
      if (data.length !== 0) {
        // 判断密码是否正确
        let bob = data.some(item => {
          return item.password == pass;
        });

        if (bob) {
          sql("select * from guanli where username=?", [uname], function (data) {
            console.log("上次登陆时间：", moment(data[0].time).format('YYYY-MM-DD,h:mm:ss a'));
            //更新登陆时间
            let newTime = new Date();
            sql("update guanli set  time = ? where username=?", [newTime, uname], function (data) { })
            let username = data[0].username;
            let key = data[0].key;
            res.send({
              bo: 1,
              ti: `/admin/index.html`,
              username: username
            });
          })

        } else {
          res.send({ bo: 3, ti: "管理员密码错误" });
        }
      } else {
        res.send({ bo: 2, ti: "管理员用户名错误" });
      }
    })

  } else {
    res.send({ bo: 2, ti: "账号密码不能为空" });
  }

})



// 普通用户管理信息获取
router.get("/user", function (req, res, next) {
  let { cons1 } = req.query;
  sql("select count(*) from userinfo", [], function (num) {
    let nums = num[0]["count(*)"];
    let cons = Math.ceil(nums / 7);
    sql(`select * from userinfo limit ${(cons1 - 1) * 7},7`, [], function (data) {
      data.forEach((item) => {
        item.time = moment(item.time).format('YYYY-MM-DD,h:mm:ss a')
      });
      res.send({
        cons,
        data,
        nums,
        cons1
      })
    })
  })
})

// 模糊查询
router.get("/sou", function (req, res, next) {
  let { content } = req.query;
  let contents = `%${content}%`;
  sql("select * from userinfo where username like ? or tel like ? ", [contents, contents], function (data) {
    data.forEach((item) => {
      item.time = moment(item.time).format('YYYY-MM-DD,h:mm:ss a')
    });
    res.send(data)
  })

})

// 用户添加
router.post("/user_add", upload.single("img"), function (req, res, next) {
  let file = req.file;
  let { username, tel, password } = req.body;
  if (file) {
    let oldUrl = file.path;
    let newUrl = file.destination + file.originalname;
    fs.rename(oldUrl, newUrl, function (err) { })
    let url = "/images/" + file.originalname;
    let time = new Date();
    if (username == "" && tel == "" && password == "") {
      res.send(`
                  <script>
                  alert("信息不能为空")
                  history.go(-1);
                  </script> 
                 `)
    } else {
      sql("select * from userinfo where username=? or tel=?", [username, tel], function (data) {
        if (data.length == 0) {
          if (/^[1][3,4,5,7,8][0-9]{9}$/.test(tel)) {
            sql("insert into userinfo values (null,?,?,1,?,?,?,?)", [username, password, tel, url, time, time], function (data) {
              if (data.affectedRows) {
                res.redirect("/admin/user.html")
              }
            })
          } else {
            res.send(`
                  <script>
                  alert("号码格式错误")
                  history.go(-1);
                  </script> 
                 `)
          }
        } else {
          res.send(`
                  <script>
                  alert("用户已存在")
                  history.go(-1);
                  </script> 
                 `)
        }
      })

    }
  } else {
    res.send(`
                  <script>
                  alert("未上传图片")
                  history.go(-1);
                  </script> 
                 `)
  }




})


// 用户修改
router.post("/user_update", upload.single("img"), function (req, res, next) {
  let file = req.file;
  let { id, username, tel, password } = req.body;
  if (file) {
    let oldUrl = file.path;
    let newUrl = file.destination + file.originalname;
    fs.rename(oldUrl, newUrl, function (err) { })
    let url = "/images/" + file.originalname;
    let time = new Date();
    if (username == "" && tel == "" && password == "") {
      res.send(`
                  <script>
                  alert("信息不得为空")
                  history.go(-1);
                  </script> 
                 `)
    } else {
      if (/^[1][3,4,5,7,8][0-9]{9}$/.test(tel)) {
        sql("update userinfo set username=?,password=?,tel=?,url=?,times=? where id=?", [username, password, tel, url, time, id], function (data) {
          if (data.affectedRows) {
            res.redirect("/admin/user.html")
          }
        })
      } else {
        res.send(`
                  <script>
                  alert("号码格式错误")
                  history.go(-1);
                  </script> 
                 `)
      }
    }
  } else {
    let time = new Date();
    if (username == "" && tel == "" && password == "") {
      res.redirect("/admin/user_add.html")
    } else {
      if (/^[1][3,4,5,7,8][0-9]{9}$/.test(tel)) {
        sql("update userinfo set username=?,password=?,tel=?,times=? where id=?", [username, password, tel, time, id], function (data) {
          if (data.affectedRows) {
            res.redirect("/admin/user.html")
          }
        })
      } else {
        res.send(`
        <script>
        alert("号码格式错误")
        history.go(-1);
        </script> 
       `)
      }
    }
  }


})


// 用户冻结
router.get("/dong", function (req, res, next) {
  let { id } = req.query;
  sql("update userinfo set status=0 where id=?", [id], function (data) {
    if (data.affectedRows) {
      res.send({
        code: 1
      })
    }
  })
})

// 用户解结
router.get("/qi", function (req, res, next) {
  let { id } = req.query;
  sql("update userinfo set status=1 where id=?", [id], function (data) {
    if (data.affectedRows) {
      res.send({
        code: 1
      })
    }
  })
})

// 用户注销
router.get("/desl", function (req, res, next) {
  let { id } = req.query;
  sql("delete from  userinfo where id=?", [id], function (data) {
    if (data.affectedRows) {
      res.send({
        code: 1
      })
    }
  })
})









// 普通管理员管理信息获取
router.get("/guanli", function (req, res, next) {
  let { cons1 } = req.query;
  sql("select count(*) from guanli", [], function (num) {
    let nums = num[0]["count(*)"];
    let cons = Math.ceil(nums / 7);
    sql(`select * from guanli limit ${(cons1 - 1) * 7},7`, [], function (data) {
      data.forEach((item) => {
        item.time = moment(item.time).format('YYYY-MM-DD,h:mm:ss a')
      });
      res.send({
        cons,
        data,
        nums,
        cons1
      })
    })
  })
})

// 模糊查询
router.get("/guanli_sou", function (req, res, next) {
  let { content } = req.query;
  let contents = `%${content}%`;
  sql("select * from guanli where username like ? or tel like ? ", [contents, contents], function (data) {
    data.forEach((item) => {
      item.time = moment(item.time).format('YYYY-MM-DD,h:mm:ss a')
    });
    res.send(data)
  })

})

//普通管理员添加
router.post("/guanli_add", upload.single("img"), function (req, res, next) {
  let file = req.file;
  let { username, tel, password } = req.body;
  if (file) {
    let oldUrl = file.path;
    let newUrl = file.destination + file.originalname;
    fs.rename(oldUrl, newUrl, function (err) { })
    let url = "/images/" + file.originalname;
    let time = new Date();
    if (username == "" && tel == "" && password == "") {
      res.send(`
              <script>
              alert("信息不得为空")
              history.go(-1);
              </script> 
  `)
    } else {
      sql("select * from guanli where username=? or tel=?", [username, tel], function (data) {
        if (data.length == 0) {
          if (/^[1][3,4,5,7,8][0-9]{9}$/.test(tel)) {
            sql("insert into guanli values (null,?,?,1,?,?,?)", [username, password, tel, url, time], function (data) {
              if (data.affectedRows) {
                res.redirect("/admin/guanli.html")
              }
            })
          } else {
            res.send(`
                  <script>
                  alert("号码格式错误")
                  history.go(-1);
                  </script> 
                 `)
          }
        } else {
          res.send(`
                  <script>
                  alert("用户已存在")
                  history.go(-1);
                  </script> 
                 `)
        }
      })

    }
  } else {
    res.send(`
    <script>
    alert("未上传图片")
    history.go(-1);
    </script> 
  `)
  }




})


// 普通管理员修改
router.post("/guanli_update", upload.single("img"), function (req, res, next) {
  let file = req.file;
  let { id, username, tel, password } = req.body;
  if (file) {
    let oldUrl = file.path;
    let newUrl = file.destination + file.originalname;
    fs.rename(oldUrl, newUrl, function (err) { })
    let url = "/images/" + file.originalname;
    let time = new Date();
    if (username == "" && tel == "" && password == "") {
      res.send(`
      <script>
      alert("信息不得为空")
      history.go(-1);
      </script> 
    `)
    } else {
      if (/^[1][3,4,5,7,8][0-9]{9}$/.test(tel)) {
        sql("update guanli set username=?,password=?,tel=?,url=?,time=? where id=?", [username, password, tel, url, time, id], function (data) {
          if (data.affectedRows) {
            res.redirect("/admin/guanli.html")
          }
        })
      } else {
        res.send(`
        <script>
        alert("电话号码格式错误")
        history.go(-1);
        </script> 
      `)
      }
    }
  } else {
    let time = new Date();
    if (username == "" && tel == "" && password == "") {
      res.send(`
      <script>
      alert("信息不得为空")
      history.go(-1);
      </script> 
    `)
    } else {
      if (/^[1][3,4,5,7,8][0-9]{9}$/.test(tel)) {
        sql("update guanli set username=?,password=?,tel=?,time=? where id=?", [username, password, tel, time, id], function (data) {
          if (data.affectedRows) {
            res.redirect("/admin/guanli.html")
          }
        })
      } else {
        res.send(`
        <script>
        alert("电话号码格式错误")
        history.go(-1);
        </script> 
      `)
      }
    }
  }


})


// 普通管理员冻结
router.get("/guanli_dong", function (req, res, next) {
  let { id } = req.query;
  sql("update guanli set status=0 where id=?", [id], function (data) {
    if (data.affectedRows) {
      res.send({
        code: 1
      })
    }
  })
})

// 普通管理员解冻
router.get("/guanli_qi", function (req, res, next) {
  let { id } = req.query;
  sql("update guanli set status=1 where id=?", [id], function (data) {
    if (data.affectedRows) {
      res.send({
        code: 1
      })
    }
  })
})

//普通管理员注销
router.get("/guanli_desl", function (req, res, next) {
  let { id } = req.query;
  sql("delete from  guanli where id=?", [id], function (data) {
    if (data.affectedRows) {
      res.send({
        code: 1
      })
    }
  })
})


module.exports = router;
